import axios from 'axios'
import router from '../router'
import cookieUtil from '../util/cookie'

axios.defaults.baseURL = "/api/"
const http = axios.create()

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import Vue from 'vue'
Vue.use(ElementUI);
//拦截器
http.interceptors.request.use(config => {
  console.log("请求拦截");
  if(config.url.startsWith("/oauth/token?grant_type=password")){
    return config
  }
  //携带token
  let token = cookieUtil.getCookie("authorization")
  let refresh = cookieUtil.getCookie("refresh")
  if(token){
    config.headers.Authorization = "Bearer " + token
  }

  if(refresh){
    config.headers.RefreshToken = refresh
  }
  return config
})

http.interceptors.response.use(response => {
  if(response.data.code == 403){
    router.push("/")
  }
  if (response.data.code == 401) {
    Vue.prototype.$message({
      message: '抱歉您没有权限访问',
      type: 'warning'
    });
  }
  console.log("响应拦截");
   //获取token refresh 如果有则放入cookie
  let token = response.data.access_token
  let refresh = response.data.refresh_token

  //判断是否有值
  if(token){
    document.cookie = "authorization=" + token;
  }      
  if(refresh){
    document.cookie = "refresh=" + refresh;
  }
  return response
})


export default http